<template>
  <div>
    <a-card :bordered="false">
      <f-search-form :more="true" @searchHandler="searchHandler">
        <f-search-form-item label="状态"  ref="syncStatusRef"  name="status" type="select" :data="statusData" @change="typeChange" />
        <f-search-form-item label="项目代码" name="projectCode" slot="advanced" />
        <f-search-form-item label="项目名称" name="projectName" />
        <f-search-form-item label="专业代码" name="majorCode" slot="advanced" />
        <f-search-form-item label="专业名称" name="majorName" slot="advanced" />
        <f-search-form-item label="工程包代码" name="packageNo" slot="advanced" />
        <f-search-form-item label="工程包名称" name="packageName" slot="advanced" />
        <f-search-form-item label="领料申请人" name="userName" slot="advanced" />
        <f-search-form-item label="领料申请时间" name="appTime" slot="advanced" />
        <f-search-form-item label="需求计划日期" name="receivedDate" slot="advanced" />
        <f-search-form-item label="预留号" name="reserveNo" slot="advanced" />
        <f-search-form-item label="预留行号" name="reserveRow" slot="advanced" />
        <f-search-form-item label="SAP同步消息" name="msgtxFromSap" slot="advanced" />
        <f-search-form-item label="班组编码" name="supplierCode" slot="advanced" />
        <f-search-form-item label="班组名称" name="supplierName" slot="advanced" />
        <f-search-form-item label="证抬头文本" name="bktxt" slot="advanced" />
      </f-search-form>
      <f-table
        ref="table"
        rowKey="recDecId"
        :exportBtn="false"
        :multiple="true"
        :operator="operator"
        :params="queryParam"
        :api="api.recDeliReqConf"
        :scroll="{ x: 1300, y: 500 }"
        :dataSource="dataSource"
        :showSetting="true"
        :tableColumns="columns"
      >
        <!--        <a slot="budatTitle" slot-scope="text">{{ text }}</a>-->
        <!--        <span slot="budatTitle">过账日期</span>-->
        <!-- 编辑 -->
        <template v-for="col in editSlots" :slot="col" slot-scope="text, record, index" :row-selection="rowSelection">
          <div :key="col">
            <a-date-picker
              v-if="editingKey === record.recDecId && col === 'budat'"
              type="date"
              style="width: 100%"
              v-model="budat"
              @change="handleChange(budat, record.recDecId, col, record)"
            ></a-date-picker>
            <a-date-picker
              v-else-if="editingKey === record.recDecId && col === 'bldat'"
              type="date"
              style="width: 100%"
              v-model="bldat"
              @change="handleChange(bldat, record.recDecId, col, record)"
            ></a-date-picker>
            <a-input
              v-else-if="editingKey === record.recDecId && col === 'bktxt'"
              style="margin: -5px 0; background-color: #ffedd9"
              :value="text"
              @change="(e) => handleChange(e.target.value, record.recDecId, col, record)"
            />
            <a-select
              v-else-if="editingKey === record.recDecId && col == 'lgort'"
              style="width: 130px; background-color: #ffedd9"
              showSearch
              optionFilterProp="children"
              v-model="lgort"
              @change="handleChange(lgort, record.recDecId, col, record)"
            >
              <a-select-option v-for="item in lgorts" :key="item.dicDataValue" :value="item.dicDataValue">
                {{ item.dicDataTitle }}
              </a-select-option>
            </a-select>
            <a-input
              v-else-if="editingKey === record.recDecId && col === 'deliveryNumThis'"
              style="margin: -5px 0; background-color: #ffedd9"
              :value="text"
              @change="(e) => handleChange(e.target.value, record.recDecId, col, record)"
            />

            <!--            <a-input v-else-if="editingKey === record.recDecId && col === 'lgort'" style="margin: -5px 0"-->
            <!--                     :value="text" @change="(e) => handleChange(e.target.value, record.recDecId, col,record)"/>-->
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template slot="operation" slot-scope="text, record, index">
          <template>
            <span v-if="editingKey === record.recDecId">
              <a @click="() => edit(record, record.recDecId)">确认</a>
            </span>
            <span v-else-if="editingKey === '' && record.status == '0' ">
              <a @click="() => edit(record, record.recDecId)">编辑</a>
            </span>
            <span v-else> - </span>
          </template>
        </template>
        <!-- 状态标识 -->
        <a-tag v-if="status === '0'" color="geekblue" slot="status" slot-scope="status">
          {{ status | formatSyncStatus }}
        </a-tag>
        <a-tag v-else-if="status === '1'" color="green" slot="status" slot-scope="status">
          {{ status | formatSyncStatus }}
        </a-tag>
        <a-tag v-else-if="status === '2'" color="volcano" slot="status" slot-scope="status">
          {{ status | formatSyncStatus }}
        </a-tag>
        <!-- <a-tag v-else-if="syncStatus === '2'" color="green" slot="syncStatus" slot-scope="syncStatus">
          {{ syncStatus | formatSyncStatus }}
        </a-tag>
        <a-tag v-else-if="syncStatus === '3'" color="volcano" slot="syncStatus" slot-scope="syncStatus">
          {{ syncStatus | formatSyncStatus }}
        </a-tag>
        <a-tag v-else color="volcano" slot="syncStatus" slot-scope="syncStatus">
          {{ syncStatus | formatSyncStatus }}
        </a-tag> -->

        <span slot="createTime" slot-scope="createTime">
          {{ createTime | format2 }}
        </span>
        <span slot="receivedD7ate" slot-scope="receivedDate">
          {{ receivedDate | format2 }}
        </span>
      </f-table>
      <brdr-drawer ref="drawer"></brdr-drawer>
    </a-card>
    <div v-if="visible">
      <a-modal
        title="出库选择"
        :visible="visible"
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <span>过账日期：</span>
        <a-date-picker
          name="postDate"
          type="date"
          style="width: 85%; margin-bottom: 15px"
          v-model="postDate"
          @change="dataValueChangeForPostDate"
        ></a-date-picker>
        <span>凭证日期：</span>
        <a-date-picker
          name="cerDate"
          type="date"
          style="width: 85%; margin-bottom: 15px"
          v-model="cerDate"
          @change="dataValueChangeForcerDate"
        ></a-date-picker>
        <span>抬头文本：</span>
        <a-input name="cerTxt" style="width: 85%; margin-bottom: 15px" @change="valueChange" />
      </a-modal>
    </div>
  </div>
</template>
<script>
import brdrDrawer from './recDeliReqConf_drawer.vue'
import api from './js/api'
import moment from 'moment'
import { formatDate, formatDate2, formatReqStatus } from '../common/data'

export default {
  name: 'TableList',
  components: {
    brdrDrawer,
  },
  data() {
    const me = this
    //操作按钮
    const operator = []
    operator.push({
      name: '出库驳回',
      icon: 'close',
      that: this,
      batch: true,
      handler: function (table, that) {
        var errMsg = ''
        let selectedRows = that.$refs.table.getSelectedRows()
        selectedRows.forEach(function(rowData){
            if(rowData['status'] == '1') {
              errMsg = '已关闭的领料单不可驳回！'
              return false
            } else if(rowData['deliveryNumThis'] > 0) {
              errMsg = '已填写本次出库数量不可驳回！'
              return false
            } else if(rowData['issuedQty'] > 0) {
              errMsg = '已出库不可驳回！'
              return false
            }
        })
        if(errMsg != '') {
          that.$message.warn(errMsg)
          return
        }

        that.reqCancel(that.dataSource)
      },
    })
    operator.push({
      name: '出库',
      icon: 'check-circle',
      that: this,
      batch: true,
      handler: function (table, that) {
        if (that.editingKey != '') {
          that.$message.warn('还有未点击确认的出库信息。')
          return
        }
        var errMsg = ''
        let selectedRows = that.$refs.table.getSelectedRows()
        selectedRows.forEach(function(rowData){
            if(rowData['status'] == '1') {
              errMsg = '请不要选择已关闭的领料单！'
              return false
            } 
            if(rowData['lgort'] == '') {
              errMsg = '出库未选择！'
            } 
            if(rowData['deliveryNumThis'] == 0) {
              errMsg += '出库数量未选择！'
            }
            if(errMsg != '') {
              return false
            }
        })
        if(errMsg != '') {
          that.$message.warn(errMsg)
          return
        }
        that.visible = true
        // that.saveForRecDeliReqConf()
      },
    })
    // operator.push({
    //   name: 'SAP同步',
    //   icon: 'sync',
    //   that: this,
    //   batch: true,
    //   handler: function (table, that) {
    //     that.syncSap(that.dataSource)
    //   },
    // })

    // operator.push({
    //   name: '删除',
    //   icon: 'delete',
    //   batch: true,
    //   handler: function(table) {
    //     table.remove()
    //   }
    // })
    return {
      api: Object.assign(api, this.api),
      statusData: [{ label: '出库单执行中', value: 0 }, { label: '出库单关闭', value: 1 }, { label: '出库驳回', value: 2 }],
      lgorts: [],
      visible: false,
      confirmLoading: false,
      postDate: '',
      cerDate: '',
      cerTxt: '',
      editingKey: '',
      recDecId: '',
      //列表初始化查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          width: 150,
          scopedSlots: { customRender: 'status' },
          sorter: (a, b) => a.status.length - b.status.length,
        },
        {
          title: '项目代码',
          align: 'center',
          dataIndex: 'projectCode',
          width: 150,
          sorter: (a, b) => a.projectCode.length - b.projectCode.length,
        },
        {
          title: '项目名称',
          align: 'center',
          dataIndex: 'projectName',
          width: 280,
          sorter: (a, b) => a.projectName.length - b.projectName.length,
        },
        {
          title: '专业代码',
          align: 'center',
          dataIndex: 'majorCode',
          width: 150,
          sorter: (a, b) => a.majorCode.length - b.majorCode.length,
        },
        {
          title: '专业名称',
          align: 'center',
          dataIndex: 'majorName',
          width: 150,
          sorter: (a, b) => a.majorName.length - b.majorName.length,
        },
        {
          title: '工程包代码',
          align: 'center',
          dataIndex: 'packageNo',
          width: 150,
          sorter: (a, b) => a.packageNo.length - b.packageNo.length,
        },
        {
          title: '工程包名称',
          align: 'center',
          dataIndex: 'packageName',
          width: 150,
          sorter: (a, b) => a.packageName.length - b.packageName.length,
        },
        {
          title: '领料申请人',
          align: 'center',
          dataIndex: 'userName',
          width: 150,
          sorter: (a, b) => a.userName.length - b.userName.length,
        },
        {
          title: '领料申请时间',
          align: 'center',
          dataIndex: 'createTime',
          width: 150,
          scopedSlots: { customRender: 'createTime' },
          sorter: (a, b) => a.createTime.length - b.createTime.length,
        },
        {
          title: '本次采购数量',
          align: 'center',
          dataIndex: 'purchaseNum',
          width: 150,
          sorter: (a, b) => a.purchaseNum.length - b.purchaseNum.length,
        },
        {
          title: '在途数量',
          align: 'center',
          dataIndex: 'onLineNum',
          width: 150,
          sorter: (a, b) => a.onLineNum.length - b.onLineNum.length,
        },
        {
          title: '到货数量',
          align: 'center',
          dataIndex: 'receiveNum',
          width: 150,
          sorter: (a, b) => a.receiveNum.length - b.receiveNum.length,
        },
        {
          title: '需求计划日期',
          align: 'center',
          dataIndex: 'receivedDate',
          width: 150,
          scopedSlots: { customRender: 'receivedDate' },
          sorter: (a, b) => a.receivedDate.length - b.receivedDate.length,
        },
        {
          title: '流水号',
          align: 'center',
          dataIndex: 'recDecId',
          width: 100,
          sorter: (a, b) => a.recDecId.length - b.recDecId.length,
        },
        {
          title: '预留号',
          align: 'center',
          dataIndex: 'reserveNo',
          width: 120,
          sorter: (a, b) => a.reserveNo.length - b.reserveNo.length,
        },
        {
          title: '预留行号',
          align: 'center',
          dataIndex: 'reserveRow',
          width: 120,
          sorter: (a, b) => a.reserveRow.length - b.reserveRow.length,
        },
        {
          title: 'SAP同步消息',
          align: 'center',
          dataIndex: 'msgtxFromSap',
          width: 120,
          sorter: (a, b) => a.msgtxFromSap.length - b.msgtxFromSap.length,
        },
        {
          title: '班组编码',
          align: 'center',
          dataIndex: 'supplierCodeForRecord',
          width: 150,
          sorter: (a, b) => a.supplierCodeForRecord.length - b.supplierCodeForRecord.length,
        },
        {
          title: '班组名称',
          align: 'center',
          dataIndex: 'supplierNameForRecord',
          width: 150,
          sorter: (a, b) => a.supplierNameForRecord.length - b.supplierNameForRecord.length,
        },
        {
          title: '已申请领料量',
          align: 'center',
          dataIndex: 'recNumThis',
          width: 150,
          sorter: (a, b) => a.recNumThis.length - b.recNumThis.length,
        },
        {
          title: '可出库数量',
          align: 'center',
          dataIndex: 'availableQty',
          width: 150,
          sorter: (a, b) => a.availableQty.length - b.availableQty.length,
        },
        {
          title: '累计出库量',
          align: 'center',
          dataIndex: 'issuedQty',
          width: 150,
          sorter: (a, b) => a.issuedQty.length - b.issuedQty.length,
        },
        // {
        //   title: '过帐日期',
        //   align: 'center',
        //   dataIndex: 'budat',
        //   width: 150,
        //   // scopedSlots: {
        //   //   customRender: 'budat'
        //   // },
        //   sorter: (a, b) => a.budat.length - b.budat.length
        // },
        // {
        //   title: '凭证日期',
        //   align: 'center',
        //   dataIndex: 'bldat',
        //   width: 150,
        //   // scopedSlots: {
        //   //   customRender: 'bldat'
        //   // },
        //   sorter: (a, b) => a.bldat.length - b.bldat.length
        // },
        // {
        //   title: '抬头文本',
        //   align: 'center',
        //   dataIndex: 'bktxt',
        //   width: 150,
        //   // scopedSlots: {
        //   //   customRender: 'bktxt'
        //   // },
        //   sorter: (a, b) => a.bktxt.length - b.createTime.length
        // },
        {
          title: '库存地点',
          align: 'center',
          dataIndex: 'lgort',
          width: 180,
          scopedSlots: {
            customRender: 'lgort',
          },
          sorter: (a, b) => a.lgort.length - b.lgort.length,
        },
        {
          title: '本次出库量',
          align: 'center',
          dataIndex: 'deliveryNumThis',
          scopedSlots: {
            customRender: 'deliveryNumThis',
          },
          width: 120,
          sorter: (a, b) => a.deliveryNumThis.length - b.deliveryNumThis.length,
        },
        {
          title: '操作',
          align: 'center',
          fixed: 'right',
          dataIndex: 'action',
          scopedSlots: { customRender: 'operation' },
          width: 150,
        },
      ],
      dataSource: [],
      // editSlots: ['budat', 'bldat', 'bktxt', 'lgort'],
      editSlots: ['lgort', 'deliveryNumThis'],
      operator: operator,
    }
  },
  filters: {
    format(time) {
      return formatDate(time, 'yyyy-MM-dd')
    },
    format2(time) {
      return formatDate2(time, 'yyyy-MM-dd')
    },
    formatSyncStatus(status) {
      return formatReqStatus(status)
    },
  },
  created() {
    this.http.get(this, {
      url: this.api.recDeliReqConf.getLgortsFromDic,
      data: {
        docTypes: 'docTypes',
      },
      success: function (me, data) {
        me.lgorts = data
      },
    })
  },
  methods: {
    dataValueChangeForPostDate(dates, dateStrings) {
      this.postDate = dateStrings
    },
    dataValueChangeForcerDate(dates, dateStrings) {
      this.cerDate = dateStrings
    },
    valueChange(val) {
      if (val.target.name === 'cerTxt') {
        this.cerTxt = val.data
      }
      console.log(val)
    },
    handleOk(e) {
      this.confirmLoading = true
      setTimeout(() => {
        this.saveForRecDeliReqConf()
        this.confirmLoading = false
        this.visible = false
      }, 2000)
    },
    handleCancel(e) {
      this.visible = false
    },
    moment,
    getCurrentData() {
      return new Date().toLocaleDateString()
    },
    getSelectedRowKey() {
      return this.$refs.table.getSelectedRowKey()
    },
    edit(record, key) {
      if (this.editingKey === key) {
        this.editingKey = ''
        if(record["deliveryNumThis"] == '' || record["deliveryNumThis"] == '0') {
            return
        }
        if (this.dataSource.length !== 0) {
          this.dataSource.forEach(function (data) {
            if (record['availableQty'] <= data['deliveryNumThis']) {
              data['deliveryNumThis'] = record['availableQty']
            } else if(data['deliveryNumThis'] <= 0) {
              data['deliveryNumThis'] = 0
            }
          })

          this.axios({
            url: this.api.recDeliReqConf.update,
            method: 'post',
            data: this.dataSource,
          })
            .then((data) => {
              this.lgort = ''
              this.editingKey = ''
              console.log(data)
              this.$message.success('操作成功')
              this.$refs.table.refresh()
            })
            .catch(function (err) {
              if (err) {
                this.editingKey = ''
                console.log(err)
              }
            })
        }
      } else {
        this.editingKey = key
        record["lgort"] = ''
        record["deliveryNumThis"] = ''
      }
    },
    handleChange(value, key, column, record) {
      const newData = [...this.dataSource]
      const target = newData.filter((item) => key === item.recDecId)[0]
      record[column] = value
      if (target) {
        target[column] = value
        newData['recDecId'] = key
        this.dataSource = newData
      } else {
        const newData2 = {}
        newData2['recDecId'] = key
        newData2[column] = value
        this.dataSource.push(newData2)
      }
    },
    saveForRecDeliReqConf() {
      let selectIdsVal = this.$refs.table.getSelectedRowKey()
      this.axios({
        url: this.api.recDeliReqConf.add,
        method: 'post',
        data: {
          selectIds: selectIdsVal,
          postDate: this.postDate,
          cerDate: this.cerDate,
          cerTxt: this.cerTxt,
        },
      })
        .then((data) => {
          this.editingKey = ''
          console.log(data)
          this.$message.success('操作成功')
          this.$refs.table.refresh()
          selectIdsVal = []
          this.$refs.table.clearSelected()
        })
        .catch(function (err) {
          if (err) {
            this.editingKey = ''
            console.log(err)
          }
        })
    },
    syncSap(dataSource) {
      const selectIds = this.$refs.table.getSelectedRowKey()
      console.log(selectIds)
    },
    reqCancel(dataSource) {
      let selectIds = this.$refs.table.getSelectedRowKey()
      console.log(selectIds)
      this.axios({
        url: this.api.recDeliReqConf.reqCancel,
        method: 'post',
        data: selectIds,
      })
        .then((data) => {
          this.editingKey = ''
          console.log(data)
          this.$message.success('操作成功')
          this.$refs.table.refresh()
          selectIds = []
          this.$refs.table.clearSelected()
        })
        .catch(function (err) {
          if (err) {
            this.editingKey = ''
            console.log(err)
          }
        })
    },
    typeChange(val) {
      this.detailsParams.status = val
      // this.refs.syncStatusRef.initData(this.queryParam)
    }
  },
}
</script>
